<template>
  <ul class="list">
    <li class="item" 
    v-for="item of letters" 
    :key="item"
    :ref="item"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
    @click="handleLetterClick"
    >{{item}}</li>
  </ul>
</template>

<script>
export default {
    name:'CityAlphabet',
    props:{
      cities:Object
    },
    computed:{
      letters(){
        const letters = []
        for(let i in this.cities){
          letters.push(i)
        }
        return letters
      }
    },
    data(){
      return{
        touchStatus:false,
        startY:0,
        timer:null
      }
    },
    updated(){
      //获取A元素距离顶部的高度
      this.startY = this.$refs['A'][0].offsetTop
    },  
    methods:{
      handleLetterClick(e){
        console.log(e.target.innerText)
        this.$emit("change",e.target.innerText)//向外传递事件,每次触发handleLetterClick函数都会触发这个事件，然后再city组件中监听设个事件 "change"就相当于这个事件的名字
      },
      handleTouchStart(){
        this.touchStatus = true
      },
      handleTouchMove(e){
        if(this.touchStatus){
          if(this.timer){
            clearTimeout(this.timer)//数据截流
          }
          //touches 属性返回 Touch 对象数组，当前触摸面的每个手指对应一个对象。
          //clientX和clientY与x，y一样的，都是客户区域坐标，指鼠标的坐标，以浏览器显示区域的左上角开始
          this.timer = setTimeout(() =>{//如果16ms内没有再次触发这个函数，才会让函数执行
            const touchY = e.touches[0].clientY - 79
            const index = Math.floor((touchY - this.startY) / 20)
            if(index >= 0 && index < this.letters.length){
              this.$emit('change',this.letters[index])
            }
          },8)
        }
      },
      handleTouchEnd(){
        this.touchStatus = false
      }
    }
}
</script>

<style lang="stylus" scoped>
@import "~styles/varibles.styl"
.list{
    display: flex
    flex-direction: column
    justify-content: center
    width: 0.4rem
    position :absolute
    top:1.68rem
    right: 0
    bottom: 0

}
.item{
    line-height: .4rem
    text-align: center
    color: $bgColor
}

</style>